const Controller = require('pages/controllers/controllers.js').controller;


App({
  onLaunch: function () {
    let systemInfo = wx.getSystemInfoSync()
    // px转换到rpx的比例
    let pxToRpxScale = 750 / systemInfo.windowWidth;
    // 状态栏的高度
    let ktxStatusHeight = systemInfo.statusBarHeight * pxToRpxScale
    // 导航栏的高度
    let navigationHeight = 44 * pxToRpxScale
    this.globalData.topNavigationHeight = ktxStatusHeight + navigationHeight
    let that=this;
    wx.getSystemInfo({
      success:  function (res)  {
      console.log(res)
      // 获取手机
      that.globalData.navHeight = res.statusBarHeight + 46;
      let model = res.model;
      if (model.search('iPhone X') != -1 || model.search('iPhone 11') != -1) {
        that.globalData.isIphoneX = true
       }
       wx.setStorageSync('modelmes', model)
      },
    })

    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    //获取token
    let token = wx.getStorageSync('logintoken') || '';

    //优先判断token
    // this.GetLogin();
    if (token) {
      //延时判断微信服务器Session状态
      setTimeout(() => {
        wx.checkSession({
          success: () => {
            //session_key 未过期，并且在本生命周期一直有效
          },
          fail: () => {
            // session_key 已经失效，需要重新执行登录流程
            // this.GetLogin();
          }
        });
      }, 1500);
    } else {
      //无token，直接登录
      // this.GetLogin();

    }
    // wx.getUpdateManager 在 1.9.90 才可用，请注意兼容
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否马上重启小程序？',
          success: function (res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate()
            }
          }
        });
      }
    });
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否马上重启小程序？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      });
    })
    updateManager.onUpdateFailed(function () {
      wx.showModal({
        title: '已有新版本',
        content: '新版本已经上线了，请删除当前小程序，重新搜索打开',
      })
    });

    // 获取用户信息
    wx.getSetting({
      success: res => {
        console.log(res)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.wxuserInfo = res.userInfo
              wx.setStorageSync('wxuserInfo', res.userInfo)
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
              
            }
          })
        }
      }
    })
  },
  
  getCurrentPageUrl(){
    var pages = getCurrentPages()    //获取加载的页面
    var currentPage = pages[pages.length-1]    //获取当前页面的对象
    var url = currentPage.route    //当前页面url
    return url
  },
  getCurrentPageUrlWithArgs(){
      var pages = getCurrentPages()    //获取加载的页面
      var currentPage = pages[pages.length-1]    //获取当前页面的对象
      var url = currentPage.route    //当前页面url
      var options = currentPage.options || []   //如果要获取url中所带的参数可以查看options
      var token=wx.getStorageSync('logintoken') || '';
      let userInfo=wx.getStorageSync('userInfo') || '';
      if(token){
        options.parentid=userInfo.id
      }
      //拼接url的参数
      var urlWithArgs = url + '?'
      for(var key in options){
          var value = options[key]
          urlWithArgs += key + '=' + value + '&'
      }
      urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length-1)
      console.log(urlWithArgs)
      return urlWithArgs
  },
  // 保存图片到本地
  saveImg(url) {
    wx.showLoading({
      title: '保存中',
      mask: true,
    })
    var that=this;
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      success() {
        wx.getImageInfo({
            src: url,
            success: function(image) {
                /* 保存图片到相册 */
                wx.saveImageToPhotosAlbum({
                    filePath: image.path,
                    success: function() {
                        console.log('save success');
                        wx.showModal({
                            title: '保存成功',
                            content: '图片已成功保存到相册，快去分享到您的圈子吧',
                            showCancel: false
                        });
                    },
                    complete(res) {
                        console.log(res);
                        wx.hideLoading()
                    }
                });
            }
        })
      },
      complete(res) {
          wx.getSetting({
            success(res) {
              if (!res.authSetting['scope.writePhotosAlbum']) {
                  that.opensit();
                  wx.hideLoading()
              }
            }
          })
      }
    });
    
  },
  //登录请求
  GetLogin(flag) {
    wx.login({
      success: res => {
        let code = res.code
        console.log(code)
        console.log(this.globalData.parentid)
        Controller.login({
          code,
          parentId:this.globalData.parentid,
          promoterId:this.globalData.promoterid,
        }).then(res => {
          console.log('getUserInfo', res)
          if(res.data.baseData.mobile){
            wx.setStorageSync('logintoken', res.data.token)
          }
          wx.setStorageSync('logintokenlinshi', res.data.token)
          wx.setStorageSync('userInfo', res.data.baseData)
          wx.setStorageSync('sessionKey', res.data.sessionKey)
          if (this.tokenReadyCallback) {
            this.tokenReadyCallback(res);
          }
        }).catch(res=>{
          console.log(res)
        })
      }
    });
  },
  ToLogin(delta=true) {
    
    var that=this;
      if(that.globalData.islogin){
        that.globalData.islogin=false
        wx.showModal({
          title: '提示',
          content: '是否授权登录?',
          success(res) {
            that.globalData.islogin=true
            if (res.confirm) {
              that.GetLogin();
              wx.getUserProfile({
                desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                success: (res) => {
                  if(res.userInfo){
                    wx.setStorageSync('wxuserInfo', res.userInfo)
                    console.log(res)
                    that.updateUserInfo(res).then(res => {
                      wx.navigateTo({
                        url: "/pages/Login/Login"
                      })
                    })
                  }
                },
                fail:(res)=>{
                  if(delta){
                    wx.switchTab({
                      url: '/pages/Index/Index'
                    })
                  }
                }
              })
            } else if (res.cancel) {
              if(delta){
                wx.switchTab({
                  url: '/pages/Index/Index'
                })
              }
              console.log('用户点击取消')
            }
          }
        })
        
  
    }
    
  },
  goLogin(delta=true) {
    var that=this;
    if(that.globalData.islogin){
      that.globalData.islogin=false
      that.globalData.islogin=true
      that.GetLogin();
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          if(res.userInfo){
            wx.setStorageSync('wxuserInfo', res.userInfo)
            console.log(res)
            that.updateUserInfo(res).then(res => {
              wx.navigateTo({
                url: "/pages/Login/Login"
              })
            })
          }
        },
        fail:(res)=>{
          if(delta){
            wx.switchTab({
              url: '/pages/Index/Index'
            })
          }
        }
      })
    }
    
  },
  //获取授权信息
  updateUserInfo(data) {
    return new Promise((resolve, reject) => {
        Controller.updateUserInfo({
          sessionKey: wx.getStorageSync('sessionKey'),
          iv: data.iv,
          encryptedData: data.encryptedData
        })
        .then(res => {
          console.log('获取用户信息', res)
          if (res.code == 0) {
            resolve(res)
          }
        }).catch(err => {
          reject(err)
        })
    })
  },
  //获取手机号
  updatePhoneNumber(data) {
    return new Promise((resolve, reject) => {
        Controller.updatePhoneNumber({
          sessionKey: wx.getStorageSync('sessionKey'),
          iv: data.iv,
          encryptedData: data.encryptedData
        })
        .then(res => {
          console.log('获取手机号', res)
          if (res.code == 0) {
            resolve(res)
          }
        }).catch(err => {
          reject(err)
        })
    })
  },
  
  globalData: {
    promoterid:'',
    parentid:'',
    companyid:'',
    isIphoneX:false,
    statusBarHeight:20,
    islogin:true,
    sessionKey:'',
    userInfo: '',
    wxuserInfo: '',
    logintoken: '',
    navHeight: 66,
    baseUrl: Controller.url,
    topNavigationHeight: 0,
    resumeitem:'',
    quesitem:'',
  },
  tokenReadyCallback: function () {},
})